﻿using System;
using System.Windows.Forms;
using KhanhPhong.POSDeviceController;
using KhanhPhong.Helper;
using KhanhPhong.BillPrintingFormat;
using RestaurantPOSManager.DatabaseTableAdapters;
using C1.Win.C1FlexGrid;
using KhanhPhong;

namespace RestaurantPOSManager
{
    public partial class FrmMakeBill : Form
    {
        public FrmMakeBill()
        {
            InitializeComponent();
        }

        QueriesTableAdapter _que;

        private void FrmMakeBillLoad(object sender, EventArgs e)
        {
            _que = new QueriesTableAdapter();

            int? _BillCount =
                _que.func_DateBillCount(Format.NumberZero(DateTime.Now.Day) + "/" +
                                        Format.NumberZero(DateTime.Now.Month) + "/" +
                                        Format.NumberZero(DateTime.Now.Year));
            lblBillCount.Text = _BillCount < 10 ? "0" + _BillCount.ToString() : _BillCount.ToString();

            tbl_FoodTableAdapter.Fill(database.tbl_Food);
            tbl_StaffTableAdapter.Fill(database.tbl_Staff);

            cbbStaff.SelectedIndex = 0;
        }

        private void CmdMakeBillClick(object sender, EventArgs e)
        {
            string header = TranQuangKy.BillHeader(_que.func_GetCompanyName(), _que.func_GetCompanyAddress(), _que.func_GetCompanyPhone()); // Thông tin công ty
            string billInformation = TranQuangKy.BillInfo(lblBillCount.Text, txtTable.Text.Trim(), dateMakeBill.Value.ToString(), _que.func_GetStaffName(int.Parse(cbbStaff.SelectedValue.ToString()))); // Thông tin hóa đơn
            string billContent = BillDetails(); // Nội dung chi tiết hóa đơn

            string contentPrint = header + billInformation + billContent;
            
            // Lưu hóa đơn vào CSDL
            int? billId = InsertBillDb(DateTime.Parse(dateMakeBill.Value.ToString()), txtTable.Text.Trim(), int.Parse(cbbStaff.SelectedValue.ToString()), int.Parse(cbbStaff.SelectedValue.ToString()), int.Parse(txtTongTien.Value.ToString()));

            // Lưu chi tiết hóa đơn vào CSDL
            for (int i = 1; i < gridMakeBill.Rows.Count; i++)
            {
                InsertSaledDb(int.Parse(billId.ToString()), int.Parse(gridMakeBill.GetData(i, 7).ToString()), double.Parse(gridMakeBill.GetData(i, 5).ToString()), double.Parse(gridMakeBill.GetData(i, 4).ToString()));
            }

            var frmPayMoney = new FrmPayMoney
            {
                StartPosition = FormStartPosition.CenterScreen,
                Tag = txtTongTien.Value + "^" + contentPrint + "^" + lblBillCount.Text
            };
            if (frmPayMoney.ShowDialog() == DialogResult.OK)
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        // Nội dung chi tiết hóa đơn
        private string BillDetails()
        {
            // Tiêu đề cột nội dung chi tiết hóa đơn
            string colTitle = "Món".PadRight(9) + " " + "Giá".PadLeft(6) + " " + "Giảm".PadLeft(5) + " " + "SL".PadLeft(2) + " " + "Tiền".PadLeft(7);

            // Nội dung chi tiết hóa đơn
            string billContent = string.Empty;
            for (int i = 1; i < gridMakeBill.Rows.Count; i++)
            {
                string mon = Format.CorrectSizeString(gridMakeBill.GetData(i, 1).ToString(), 9, false);
                string gia = gridMakeBill.GetData(i, 3).ToString().PadLeft(6);
                string giam = gridMakeBill.GetData(i, 4).ToString().PadLeft(5);
                string soLuong = gridMakeBill.GetData(i, 5).ToString().PadLeft(2);
                string thanhTien = gridMakeBill.GetData(i, 6).ToString().PadLeft(7);

                // Thêm gạch dưới vào dòng cuối cùng
                // if (i == gridMakeBill.Rows.Count - 1) BillContent += Printer.Underline;

                billContent += mon + " " + gia + " " + giam + " " + soLuong + " " + thanhTien + "\n";
            }

            string result = Printer.Bold + colTitle + Printer.Normal + "\n" + billContent + Printer.Normal;

            return result;
        }

        private int InsertSaledDb(int billId, int foodId, double soLuong, double discount) 
        {
            return _que.sp_InsertSaled(billId, foodId, soLuong, discount);
        }

        private int? InsertBillDb(DateTime saleDate, string tableName, int billStaffId, int serviceStaffId, double totalMoney)
        {
            int? result = 0;
            _que.sp_InsertBill(saleDate, tableName, billStaffId, serviceStaffId, totalMoney, ref result);

            return result;
        }

        private void CbbFoodTextChanged(object sender, EventArgs e)
        {
            try
            {
                int iFoodId = int.Parse(cbbFood.SelectedValue.ToString());
                
                lblUnit.Text = _que.func_GetFoodUnit(iFoodId);
                txtPrice.Value = _que.func_GetFoodPrice(iFoodId).ToString();
            }
            catch (Exception)
            { }
        }

        private void FuncTongCong()
        {
            try
            {
                float fTongTien = 0;

                foreach (Row dr in gridMakeBill.Rows)
                {
                    try
                    {
                        fTongTien += float.Parse(dr[6].ToString());
                    }
                    catch (Exception)
                    { }
                }

                txtTongTien.Value = fTongTien.ToString();
            }
            catch (Exception)
            { }
        }

        private void CmdAddClick(object sender, EventArgs e)
        {
            int iFoodId = int.Parse(cbbFood.SelectedValue.ToString());
            string sFood = _que.func_GetFoodName(iFoodId);
            string sUnit = lblUnit.Text;
            float fPrice = float.Parse(txtPrice.Value.ToString());
            float fDiscount = float.Parse(txtDiscount.Value.ToString());
            float fNumber = float.Parse(txtCount.Text);
            float fTotal = (fPrice - fDiscount) * fNumber;

            object[] item = { gridMakeBill.Rows.Count, sFood, sUnit, fPrice.ToString(), fDiscount.ToString(), fNumber.ToString(), fTotal.ToString(), iFoodId };
            gridMakeBill.AddItem(item);

            FuncTongCong();
        }

        private void gridMakeBill_AfterDeleteRow(object sender, RowColEventArgs e)
        {
            FuncTongCong();
        }
    }
}
